package org.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.example.config.CookieConfig;
import org.example.dianguanjia.HttpUtils;
import org.example.entity.*;
import org.example.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.util.concurrent.Executors.*;

/**
 * ============================================================<br>
 * <p> ProjectName ：dianguanjiaexportdata </p>
 * <p> @author dongjianzhao </p>
 * <p> @date 2023/3/13 </p>
 * <p> @version ：1.0 </p>
 * ============================================================<br>
 * <p>
 * 12
 * </p>
 * ============================================================<br>
 */
@Service
@Slf4j
public class DiantiguanjiaToXitongImpl {
    /**
     * 电管家 客户设备列表
     */
     String khsblb="http://222.223.186.60:18020/energy-server/v1/restEquipDropDownController/queryDropDownByCodeType";
    /**
     * 电气联系人
     */
     String dqlxr="http://222.223.186.60:18020/energy-server/v1/baseCustController/initUpdContact";
    /**
     * 电管家 厂站管理列表等
     */
     String khdxx="http://222.223.186.60:18020/energy-server/v1/restPlantSiteController/querySiteGrid";
    /**
     * 电管家  修改页面初始化客户基本信息
     */
     String khjbxx="http://222.223.186.60:18020/energy-server/v1/baseCustController/initUpdBaseCustInfo";
    /**
     * 电管家 查询客户设备
     */
     String khsb="http://222.223.186.60:18020/energy-server/v1/restPortBaseController/queryEquipList";
     String khlb="http://222.223.186.60:18020/energy-server/v1/searchUserRestController/searchUsersInfo";
    /**
     * 电管家 客户营销用户列表
     */
    String afterAddSearch= "http://222.223.186.60:18020/energy-server/v1/userListRestController/afterAddSearch";
    /**
     * 电管家 客户地址信息 包含经纬度等  厂站管理
     */
    String querySiteGrid ="http://222.223.186.60:18020/energy-server/v1/restPlantSiteController/querySiteGrid";
    /**
     *电管家 查询下拉框数据
     */
    String queryDropDownByCodeType="http://222.223.186.60:18020/energy-server/v1/restEquipDropDownController/queryDropDownByCodeType";
    /**
     * 电管家 客户设备列表 对应设备管理
     */
    String queryEquipManagementList="http://222.223.186.60:18020/energy-server/v1/restEquipManagementController/queryEquipManagementList";
    /**
     * 电管家 客户用户定价策略、用户电价
     */
    String init="http://222.223.186.60:18020/energy-server/v1/userListRestController/init";
    /**
     * 电管家 建筑房间管理
     */
    String queryStructureByCustIdAndSiteId="http://222.223.186.60:18020/energy-server/v1/restBuildRoomManagementController/queryStructureByCustIdAndSiteId";
    /**
     * 电管家 客户回路管理列表
     */
    String queryLoopAttribute="http://222.223.186.60:18020/energy-server/v1/restLoopManagementController/queryLoopAttribute";
    /**
     * 电管家 监测点管理
     */
    String  queryMonInfoByCustNo="http://222.223.186.60:18020/energy-server/v1/restMonInfoController/queryMonInfoByCustNo";
    /**
     * 电管家 设备基本信息
     */
    String queryEquipManagementByEquipFilezInfoId="http://222.223.186.60:18020/energy-server/v1/restEquipManagementController/queryEquipManagementByEquipFilezInfoId";
     String cookie= CookieConfig.COOKIE;
   @Autowired
   private DgjInitupdcontactMapper dgjInitupdcontactMapper;
   @Autowired
   private DgjAfteraddsearchMapper dgjAfteraddsearchMapper;
   @Autowired
   private DgjQuerysitegridMapper dgjQuerysitegridMapper;
    @Autowired
    private CustInfoMapper custInfoMapper;
    @Autowired
    private CustAddrMapper custAddrMapper;
    @Autowired
    private TaxMapper taxMapper;
    @Autowired
    private DgjQuerydropdownbycodetypeMapper dgjQuerydropdownbycodetypeMapper;
    @Autowired
    private DgjQueryequipmanagementlistMapper dgjQueryequipmanagementlistMapper;
    @Autowired
    private DgjDownMapper dgjDownMapper;
    @Autowired
    private DgjQuerystructurebycustidandsiteidMapper dgjQuerystructurebycustidandsiteidMapper;
    @Autowired
    private DgjQueryequipmanagementMapper dgjQueryequipmanagementMapper;
    public void diantiguanjiaToXitongImpl(){
        //将3941条客户信息同步到数据库中
        /*for(int i=1;i<15;i++){
            spiderCustList(i);
        }*/
        //创建一个固定大小的线程池的大小 将3941条客户信息同步到数据库中
        ExecutorService threadpool = newFixedThreadPool(15);
        try {
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(1);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(2);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(3);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(4);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(5);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(6);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(7);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(8);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(9);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(10);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(11);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(12);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(13);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(14);
            });
            threadpool.execute(()->{
                System.out.println(Thread.currentThread().getName()+"ok");
                spiderCustList(15);
            });
           for (int i = 1; i < 15; i++) {
                //使用线程池之后，使用线程池来创建线程
                threadpool.execute(()->{
                    System.out.println(Thread.currentThread().getName()+"ok");
                   // spiderCustList(i);
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadpool.shutdown();
        }
       add_dgjInitupdcontact();
        add_dgjAfteraddsearch();
        add_querySiteGrid();
       // add_dgjQuerydropdownbycodetype();
        add_dgjQueryequipmanagementlist();
        add_down();
        add_queryStructureByCustIdAndSiteId();
        add_queryLoopAttribute();
        add_queryMonInfoByCustNo();
        addDgjQueryequipmanagement();

    }

    private void spiderCustList(int i) {
        List<Map<String, Object>> list = getKhListMaps(i);
        list.forEach(f->{
            String custId= (String) f.get("custId");
            khjbxx_f(custId);
        });
    }

    /**
     * 客户的设备
     */
    private void addDgjQueryequipmanagement() {
        List<DgjQueryequipmanagementlist> list = dgjQueryequipmanagementlistMapper.selectAll();
        list.forEach(l->{
            String equipFilezInfoId = l.getEquipFilezInfoId();
            Map<String,Object> pa=new HashMap<>();
            pa.put("equipFilezInfoId",equipFilezInfoId);
            String s= HttpUtils.httpPost(queryEquipManagementByEquipFilezInfoId,pa,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONObject data = (JSONObject) parse.get("data");
            if(data!=null){
                DgjQueryequipmanagement d=new DgjQueryequipmanagement();
                BeanUtil.copyProperties(data,d);
                dgjQueryequipmanagementMapper.insert(d);
            }
        });
    }

    /**
     * 没数据
     */
    private void add_queryMonInfoByCustNo() {
         /* {
            "currentPageNum": "1",
                "custNo": "2023031300008",
                "mon": "dolor in ut aliquip sunt",
                "monState": "dolore anim quis sint aliquip",
                "objType": "pariatur proident eu cupidatat adipisicing",
                "pageFlag": true,
                "pageSize": "10"
        }*/
        List<DgjAfteraddsearch> list=dgjAfteraddsearchMapper.selectAll();
        for(int i=0;i< list.size();i++){
            DgjAfteraddsearch f=list.get(i);
            Map<String,Object> pa=new HashMap<>();
            pa.put("custNo",f.getConsNo());
            pa.put("currentPageNum",1);
            pa.put("mon","");
            pa.put("monState","");
            pa.put("objType","");
            pa.put("pageFlag",true);
            pa.put("pageSize",100);
            String s= HttpUtils.httpPost(queryMonInfoByCustNo,pa,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONArray data = (JSONArray) parse.get("data");
            System.out.println(i);
            System.out.println(data);
        }
    }

    /**
     * 没数据
     */
    private void add_queryLoopAttribute() {
        List<CustInfo> list=custInfoMapper.selectAll();
        for(int i=0;i< list.size();i++){
            CustInfo f=list.get(i);
            /* {
                "currentPageNum": "1",
                    "structureId": "",
                    "siteId": "",
                    "pageSize": "10",
                    "pageFlag": "true",
                    "upLoopId": "42B9B6B3E17B495DB89B1A9F6395DAC3"
            }*/
            Map<String,Object> pa=new HashMap<>();
            pa.put("upLoopId",f.getCustId());
            pa.put("pageFlag",true);
            pa.put("pageSize",100);
            pa.put("siteId","");
            pa.put("structureId","");
            pa.put("currentPageNum","1");
            String s= HttpUtils.httpPost(queryLoopAttribute,pa,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONArray data = (JSONArray) parse.get("data");
            System.out.println(i);
            System.out.println(data);
        }
    }

    private void add_queryStructureByCustIdAndSiteId() {
        List<CustInfo> list=custInfoMapper.selectAll();
        list.forEach(f->{
            String custId = f.getCustId();
            Map<String,Object> param=new HashMap<>();
            param.put("cust_id",custId);
            List<DgjQuerysitegrid> dgjQuerysitegrids = dgjQuerysitegridMapper.selectByMap(param);
            dgjQuerysitegrids.forEach(d->{
               /* {
                    "currentPageNum": "1",
                        "pstructureId": "98A1518D99F44A9E84A79ACA62123CF1",
                        "pageSize": "10",
                        "pageFlag": "true",
                        "custId": "42B9B6B3E17B495DB89B1A9F6395DAC3",
                        "siteId": "98A1518D99F44A9E84A79ACA62123CF1"
                }*/
                Map<String,Object> pa=new HashMap<>();
                pa.put("custId",custId);
                pa.put("currentPageNum",1);
                pa.put("pstructureId",d.getSiteInfoId());
                pa.put("pageSize",100);
                pa.put("pageFlag",true);
                pa.put("siteId",d.getSiteInfoId());
                String s= HttpUtils.httpPost(queryStructureByCustIdAndSiteId,pa,cookie);
                JSONObject parse = (JSONObject) JSONObject.parse(s);
                JSONArray data = (JSONArray) parse.get("data");
                if(data!=null){
                    for(int i=0;i<data.size();i++){
                        JSONObject o = (JSONObject) data.get(i);
                        if(o!=null){
                            DgjQuerystructurebycustidandsiteid dq=new DgjQuerystructurebycustidandsiteid();
                            BeanUtil.copyProperties(o,dq);
                            dq.setCustId(custId);
                            dq.setSiteId(d.getSiteInfoId());
                            dq.setSiteName(d.getSiteName());
                            dgjQuerystructurebycustidandsiteidMapper.insert(dq);
                        }
                    }
                }


            });
        });
    }

    private void add_down() {
        List<DgjAfteraddsearch> list=dgjAfteraddsearchMapper.selectAll();
        list.forEach(f->{
           /* {
                "queryForm": {
                     "consId": "588987486"
                }
            }*/
            Map<String,Object> param=new HashMap<>();
            param.put("consId",f.getConsId());
            //页面容量
            Map<String,Map<String,Object>> p=new HashMap<>();
            p.put("queryForm",param);
            String s= HttpUtils.httpPost2(init,p,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONObject data = (JSONObject) parse.get("data");
            if(data!=null){
                JSONArray down1= (JSONArray) data.get("down1");
                JSONArray down2= (JSONArray) data.get("down2");
               String custId="";
                if(down1!=null){
                    for (int i=0;i<down1.size();i++){
                        JSONObject o = (JSONObject) down1.get(i);
                        if(o!=null){
                            DgjDown d=new DgjDown();
                            BeanUtil.copyProperties(o,d);
                            d.setConsId(f.getConsId());
                           custId=d.getCustId();
                           d.setType("down1");//策略
                            dgjDownMapper.insert(d);
                        }
                    }
                }
                if(down2!=null){
                    for (int i=0;i<down2.size();i++){
                        JSONObject o = (JSONObject) down2.get(i);
                        if(o!=null){
                            DgjDown d=new DgjDown();
                            BeanUtil.copyProperties(o,d);
                            d.setCustId(custId);
                            d.setType("down2");//用户电价
                            dgjDownMapper.insert(d);
                        }
                    }
                }
            }
        });
    }

    private void add_dgjQueryequipmanagementlist() {
        List<CustInfo> list=custInfoMapper.selectAll();
        add_dgjQueryequipmanagementlist(list,"0");
        add_dgjQueryequipmanagementlist(list,"1");
    }

    private void add_dgjQueryequipmanagementlist(List<CustInfo> list,String isMonitor) {
        list.forEach(f->{
          /*  "currentPageNum": "1",
                    "isMonitor": "0",
                    "equipType": "",
                    "equipStatus": "",
                    "equipName": "",
                    "custId": "E4FEC3B782464AA990B8F89D777A77B2",
                    "pageFlag": "true",
                    "pageSize": "10"*/
            /*isMonitor: "0"   是用能设备
            isMonitor: "1"   是采集设备*/
            Map<String,Object> param=new HashMap<>();
            param.put("currentPageNum","1");
            param.put("isMonitor",isMonitor);
            param.put("equipType","");
            param.put("equipStatus","");
            param.put("custId",f.getCustId());
            param.put("pageFlag","true");
            param.put("pageSize",100);
            String s= HttpUtils.httpPost(queryEquipManagementList,param,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONArray data = (JSONArray) parse.get("data");
            if(data!=null){
                for (Object o : data) {
                    JSONObject j=(JSONObject)o;
                    if(j!=null){
                        DgjQueryequipmanagementlist d=new DgjQueryequipmanagementlist();
                        BeanUtil.copyProperties(j,d);
                        dgjQueryequipmanagementlistMapper.insert(d);
                    }
                }
            }
        });
    }

    /**
     * 按照类型拉去下拉框的数据
     */
    private void add_dgjQuerydropdownbycodetype() {
        /**
         * 下拉框的类型
         */
        String[] type={"equipType","equipStatus","equipFrom","equipBigClass","loop_type","monState","objType",
                "bsVoltCode","bsSetMealType","bsContractState","bsPaymentState","bsBillState","promoteState","equipInstalState","status",
                "custtype","voltLevel"};
        for (String t : type) {
            getDgjQuerydropdownbycodetypeByType(t);
        }

    }

    private void getDgjQuerydropdownbycodetypeByType(String t) {
        Map<String,Object> param=new HashMap<>();
        param.put("codeType", t);
        String s= HttpUtils.httpPost(queryDropDownByCodeType,param,cookie);
        JSONObject parse = (JSONObject) JSONObject.parse(s);
        JSONArray data = (JSONArray) parse.get("data");
        for (Object o : data) {
            JSONObject j=(JSONObject)o;
            if(j!=null){
                DgjQuerydropdownbycodetype d=new DgjQuerydropdownbycodetype();
                BeanUtil.copyProperties(j,d);
                d.setCodeType(t);
                dgjQuerydropdownbycodetypeMapper.insert(d);
            }
        }
    }

    private void add_querySiteGrid() {
        List<CustInfo> list=custInfoMapper.selectAll();
        list.forEach(f->{
           /* {
                "currentPageNum": "1",
                    "custId": "E4FEC3B782464AA990B8F89D777A77B2",
                    "noOrName": "",
                    "pageFlag": "true",
                    "pageSize": "10",
                    "statusCode": ""
            }*/
            Map<String,Object> param=new HashMap<>();
            param.put("currentPageNum","1");
            param.put("custId",f.getCustId());
            param.put("pageFlag","true");
            param.put("noOrName","");
            param.put("statusCode","");
            param.put("pageSize",100);
            String s= HttpUtils.httpPost(querySiteGrid,param,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONArray data = (JSONArray) parse.get("data");
            if(data!=null){
                for (Object o : data) {
                    JSONObject j=(JSONObject)o;
                    if(j!=null){
                        DgjQuerysitegrid d=new DgjQuerysitegrid();
                        BeanUtil.copyProperties(j,d);
                        dgjQuerysitegridMapper.insert(d);
                    }
                }
            }
        });
    }

    private void add_dgjAfteraddsearch() {
        List<CustInfo> list=custInfoMapper.selectAll();
        list.forEach(f->{
          /*  {
                "queryForm": {
                "busNo": "2023031300003",
                        "orgNo": "1340309"
            }
            }*/
            Map<String,Object> param=new HashMap<>();
            param.put("busNo",f.getCustNo());
            param.put("orgNo", "13102");
            //页面容量
            Map<String,Map<String,Object>> p=new HashMap<>();
            p.put("queryForm",param);
            String s= HttpUtils.httpPost2(afterAddSearch,p,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONObject datas = (JSONObject) parse.get("data");
            JSONArray top =(JSONArray)  datas.get("top");
                for (Object o : top) {
                    JSONObject j=(JSONObject)o;
                    if(j!=null){
                        DgjAfteraddsearch d=new DgjAfteraddsearch();
                        BeanUtil.copyProperties(j,d);
                        dgjAfteraddsearchMapper.insert(d);
                    }
                }

        });
    }

    private void add_dgjInitupdcontact() {
        List<CustInfo> list=custInfoMapper.selectAll();
        list.forEach(f->{
            Map<String,Object> param=new HashMap<>();
            param.put("currentPageNum","1");
            param.put("custId",f.getCustId());
            param.put("pageSize",100);
            String s= HttpUtils.httpPost(dqlxr,param,cookie);
            JSONObject parse = (JSONObject) JSONObject.parse(s);
            JSONObject data = (JSONObject) parse.get("data");
            if(data!=null){
                JSONArray datas = (JSONArray) data.get("data");
                for (Object o : datas) {
                    JSONObject j=(JSONObject)o;
                    if(j!=null){
                        DgjInitupdcontact d=new DgjInitupdcontact();
                        BeanUtil.copyProperties(j,d);
                        dgjInitupdcontactMapper.insert(d);
                    }
                }
            }
        });
    }

    private  List<Map<String, Object>> getKhListMaps(int page) {
        Map<String,Object> param=new HashMap<>();
        param.put("baseId","");
        param.put("busNo","");
        param.put("consNo","");
        param.put("currentPageNum" ,page);
        param.put("custName", "");
        param.put("orgNo", "13102");
        //页面容量
        param.put("pageSize",300);
        param.put("statusCode","");
        Map<String,Map<String,Object>> p=new HashMap<>();
        p.put("queryForm",param);
        String s= HttpUtils.httpPost2(khlb,p,cookie);
        JSONObject parse = (JSONObject) JSONObject.parse(s);
        JSONObject datas = (JSONObject) parse.get("data");
        JSONArray userList =(JSONArray)  datas.get("usersList");
        List<Map<String,Object>> list=new ArrayList<>();
        for (int i=0;i<userList.size();i++){
            JSONObject j= (JSONObject) userList.get(i);
            String custId = (String) j.get("custId");
            String custNo = (String) j.get("custNo");
            Map<String, Object> stringObjectMap =new HashMap<>();
            stringObjectMap.put("custId",custId);
            stringObjectMap.put("custNo",custNo);
            list.add(stringObjectMap);
        }
        return list;
    }

    private  void jsonArrayToList(JSONArray jsonArray, List<Map<String, String>> list) {
        System.out.println(jsonArray.get(0));
      /*  jsonArray.forEach(j->{
            Map<String,String> map=new HashMap<>();
            list.add(map);
        });*/
    }

    private  void khjbxx_f(String custId) {
        Map<String,Object> param=new HashMap<>();
        param.put("custId",custId);
        String s= HttpUtils.httpPost(khjbxx,param,cookie);
        JSONObject parse = (JSONObject) JSONObject.parse(s);
        JSONObject data_f = (JSONObject) parse.get("data");
        JSONObject datas = (JSONObject) data_f.get("data");
        JSONObject custAddr =(JSONObject)  datas.get("custAddr");
        JSONObject tax =(JSONObject)  datas.get("tax");
        JSONObject custInfo =(JSONObject)  datas.get("custInfo");
        log.info("custAddr:{}",JSONObject.toJSON(custAddr));
        log.info("tax:{}",JSONObject.toJSON(tax));
        log.info("custInfo:{}",JSONObject.toJSON(custInfo));
        CustInfo ci=new CustInfo();
        BeanUtil.copyProperties(custInfo,ci);
        if(custInfo!=null){
            custInfoMapper.insert(ci);
        }

        CustAddr ca=new CustAddr();
        BeanUtil.copyProperties(custAddr,ca);
        if(custAddr!=null){
            custAddrMapper.insert(ca);
        }

        Tax t=new Tax();
        BeanUtil.copyProperties(tax,t);
        if(tax!=null){
            taxMapper.insert(t);
        }

    }
}
